import { customRef } from "vue";

type TRefValue = string|boolean
type TTimer = number|null

/**
 * @param {TRefValue} value
 * @param {number} delay
 * @return {customRef}
 * @Date: 2024-06-03 14:21:43
 * @Description: 自定义防抖的ref值, 通常针对于输入框(如实时搜索/过滤)/开关等,特别注意: 值不是立刻更新的
 */
export default function debounceRef<T extends TRefValue>(value: T , delay = 250) {
  let timer:TTimer = null
  return customRef((track, trigger) => ({
    get() {
      // 依赖收集
      track();
      return value
    },
    set(val:T) {
      timer && clearTimeout(timer)
      timer = setTimeout(() => {
        // 派发更新
        value = val
        trigger();
      }, delay)
    }
  }))
}